<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" :title="typeTitle"
    custom-class="mydialog" width="50%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="140px" size="small">
      <el-row gutter="40">
        <el-col :span="12">
          <el-form-item label="商销客户名称" prop="sellerName">
            <el-input v-model="openForm.sellerName" clearable placeholder="请输入商销客户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业所在地区" prop="value">
            <el-cascader v-model="openForm.value" :options="cityList" :popper-append-to-body="false"
              :props="{ value:'regionCode',label:'regionName',expandTrigger: 'hover' }" placeholder="请选择地区"
              style="width:100%" @change="handlCity" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="openForm.address" clearable placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码" prop="creditCode">
            <el-input v-model="openForm.creditCode" clearable placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="联系人" prop="userName">
            <el-input v-model="openForm.userName" clearable placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="openForm.tel" clearable placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消
        </el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  getCurrentInstance,
  inject,
  nextTick,
  reactive,
  ref,
  toRefs,
} from "vue";
import area from "@/utils/area";
import { validateVETel } from "@/utils/validate";

export default {
  name: "AgentDialog",
  props: {
    planDetailId: {
      type: Number,
      default: 0,
    },
  },
  setup(props, context) {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机码"));
      } else {
        if (validateVETel(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    };
    const validateName = async (rule, value, callback) => {
      if (value === "") {
        callback("请输入商销客户名称");
      } else {
        const aaa = await validateVEName(value);
        console.log(aaa, "----");
        if (aaa === true) {
          callback(new Error("商销客户名称已存在"));
        } else {
          callback();
        }
      }
    };
    //* ********************************
    const api = inject("api");
    const data = reactive({
      openBoole: false,
      cityList: area,
      openForm: {
        value: null,
        agentNumber: "",
        sellerName: "", // 商销客户名称
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
        address: "", // 详细地址
        userName: "", // 联系人
        tel: "", // 联系电话
        creditCode: "", // 统一信用代征码
        id: -1,
      },
      rules: {
        sellerName: [
          { required: true, validator: validateName, trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        tel: [{ required: true, validator: validateTel, trigger: "blur" }],
        value: [{ required: true, message: "请选择地区", trigger: "change" }],
      },
      openRef: null,
      typeTitle: "",
    });
    const currentInstance = getCurrentInstance();

    const handlCity = (val) => {
      if (val) {
        data.openForm.provinceCode = val[0];
        data.openForm.cityCode = val[1];
        data.openForm.areaCode = val[2];
        nextTick((_) => {
          data.openRef.clearValidate("provinceCode");
        });
      }
    };

    const validateVEName = async (val) => {
      const paramData = {
        table: "seller",
        column: "seller_name",
        column_data: val,
        id: data.openForm.id !== -1 ? data.openForm.id : "",
      };
      const booleName = ref(false);
      const res = await api.channelAgent.POTENTIALAGENT_NAME(paramData);
      if (res.code === 0) {
        if (res.data.exist === "1") {
          booleName.value = true;
        } else {
          booleName.value = false;
        }
      } else {
        booleName.value = false;
      }
      return booleName.value;
    };

    const close = () => {
      data.openBoole = false;
      handlRemove();
    };

    const handlRemove = () => {
      data.openForm.provinceCode = "";
      data.openForm.cityCode = "";
      data.openForm.areaCode = "";
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (title, row) => {
      data.openForm = {
        value: null,
        agentNumber: "",
        sellerName: "", // 商销客户名称
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
        address: "", // 详细地址
        userName: "", // 联系人
        tel: "", // 联系电话
        creditCode: "", // 统一信用代征码
        id: -1,
      };
      data.typeTitle = title;
      if (row) {
        data.openForm = JSON.parse(JSON.stringify(row));
        data.openForm.value = [
          data.openForm.provinceCode,
          data.openForm.cityCode,
          data.openForm.areaCode,
        ];
      }
      data.openBoole = true;
    };

    // 确定
    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        console.log(465465456);
        if (valid) {
          console.log(handleFormData());
          var msg = "",
            commit = undefined,
            obj = handleFormData();
          if (data.openForm.id === -1) {
            msg = "保存成功";
            commit = api.editorial.EDITORIAL_SHANGPIN_CREATE;
          }

          commit(obj).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: msg,
              });
              context.emit("succsess");
              close();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    const handleFormData = () => {
      var obj = {
        sellerName: data.openForm.sellerName, // 代理商名称
        provinceCode: data.openForm.provinceCode, // 省code
        cityCode: data.openForm.cityCode, // 市code
        areaCode: data.openForm.areaCode, // 区code
        address: data.openForm.address, // 详细地址
        userName: data.openForm.userName, // 联系人
        tel: data.openForm.tel, // 联系电话
        creditCode: data.openForm.creditCode, // 统一信用代征码
        planDetailId: props.planDetailId,
      };

      return obj;
    };

    return {
      ...toRefs(data),
      close,
      open,
      handlSubmit,
      handlCity,
      handlRemove,
      validateVEName,
      handleFormData,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
